package cc.shacocloud.luanniao.core.config

import cc.shacocloud.luanniao.core.model.po.converter.BeanToJsonStringConverter
import cc.shacocloud.luanniao.core.model.po.converter.JsonStringToBeanConverter
import cc.shacocloud.luanniao.core.service.ai.AiOptions
import cc.shacocloud.luanniao.core.service.oss.FileStoreInfo
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.convert.CustomConversions
import org.springframework.data.r2dbc.config.EnableR2dbcAuditing
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions
import org.springframework.data.r2dbc.dialect.DialectResolver
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories
import org.springframework.r2dbc.core.DatabaseClient

/**
 *
 * @author 思追(shaco)
 */
@Configuration
@EnableR2dbcAuditing
@EnableR2dbcRepositories(basePackages = ["cc.shacocloud.luanniao.core"])
class R2dbcConfiguration {

    @Bean
    @ConditionalOnMissingBean
    fun r2dbcCustomConversions(databaseClient: DatabaseClient): R2dbcCustomConversions {
        val dialect = DialectResolver.getDialect(databaseClient.getConnectionFactory())
        val converters = ArrayList<Any>(dialect.converters)
        converters.addAll(R2dbcCustomConversions.STORE_CONVERTERS)

        return R2dbcCustomConversions(
            CustomConversions.StoreConversions.of(dialect.getSimpleTypeHolder(), converters),
            getCustomConverters()
        )
    }

    /**
     * r2dbc属性 自定义转换器
     */
    fun getCustomConverters(): List<Any> {
        return listOf(
            object : BeanToJsonStringConverter<AiOptions>() {},
            object : JsonStringToBeanConverter<AiOptions>() {},
            object : BeanToJsonStringConverter<FileStoreInfo>() {},
            object : JsonStringToBeanConverter<FileStoreInfo>() {},
        )
    }

}